package middlewares

/*
 +----------------------------------------------------------------------
 + Title        : MgrAuthMiddleware
 + Author       : huwl
 + Version      : 1.0.0
 + Initial-Time : 2021-09-22
 + Last-time    : 这个文件最后修改的时间 + 修改人的名称
 + Desc         : 管理权限中间件
 +----------------------------------------------------------------------
*/
import (
	"golang-microgrpc-sharemod/gateway-api/utils"
	"strings"

	"github.com/gin-gonic/gin"
)

/**
 * 管理认证
 *
 * @author huwl
 * @date 2025/08/01 10:26:43
 */
func MgrAuthMiddleware(ctx *gin.Context) {
	authorization := ctx.Request.Header.Get("Authorization")
	if authorization == "" {
		ctx.JSON(200, gin.H{
			"code":    "401",
			"data":    nil,
			"message": "authorization token is empty",
		})

		ctx.Abort()
		return
	}

	token := strings.Split(authorization, " ")[1]
	cc, err := utils.ParseToken(token)
	if err != nil {
		if strings.Contains(err.Error(), "token is expired") {
			ctx.JSON(200, gin.H{
				"code":    "402",
				"data":    nil,
				"message": "authorization token is expired",
			})
		} else {
			ctx.JSON(200, gin.H{
				"code":    "401",
				"data":    nil,
				"message": "authorization token error",
			})
		}

		ctx.Abort()
		return
	}

	ctx.Set("account_id", cc.Id)
	ctx.Next()
}
